package com.mugcode.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mugcode.cmn.listener.DictListener;
import com.mugcode.cmn.mapper.DictMapper;
import com.mugcode.cmn.service.DictService;
import com.mugcode.entity.model.cmn.Dict;
import com.mugcode.entity.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * projectName: appointment
 * <p>
 * author: Mu
 * time: 2023/5/27 9:25
 * description:
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = query().eq("parent_id", id).list();
        dictList.stream().map(dict -> {
            dict.setHasChildren(isChildren(dict.getId()));
            return dict;
        }).collect(Collectors.toList());
        return dictList;
    }

    //导出数据字典
    @Override
    public void exportDictData(HttpServletResponse res) {
        //设置下载信息
        res.setContentType("application/vnd.ms-excel");
        res.setCharacterEncoding("utf-8");
        String fileName = "dict";
        res.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>();
        for(Dict dict:dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);
        }
        try{
            EasyExcel.write(res.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictVoList);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    //导入数据字典
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try{
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if(StringUtils.isEmpty(dictCode)){
//            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//            wrapper.eq("value",value);
//            Dict dict = baseMapper.selectOne(wrapper);
//            return dict.getName();
            return lambdaQuery().eq(Dict::getValue, value).one().getName();
        }else{
            Long parent_id = this.getDictByDictCode(dictCode).getId();
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value",value));
            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);
        List<Dict> childData = this.findChildData(dict.getId());
        return childData;
    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    //判断id下面是否有字节点
    private boolean isChildren(Long id){
        return query().eq("parent_id", id).count() > 0;
    }
}
